dayjs.extend(dayjs_plugin_utc);
dayjs.extend(dayjs_plugin_timezone);

function scSumLH(numbers) {
  const sum = numbers[0] + numbers[1];
  let dx = "小";
  let ds = "单";
  if (sum >= 6) {
    dx = "大";
  }
  if (sum % 2 == 0) {
    ds = "双";
  }
  const labels = [];
  const results = [];
  // 按顺序比较相邻的数字，计算每轮的胜负结果
  for (let i = 0; i < numbers.length; i += 2) {
    const tigerNumber = numbers[i]; // 每轮“虎”的号码
    const dragonNumber = numbers[i + 1]; // 每轮“龙”的号码
    let result;
    if (tigerNumber > dragonNumber) {
      result = "虎"; // “虎”赢
      labels.push("虎");
    } else {
      result = "龙"; // “龙”赢
      labels.push("龙");
    }
    results.push(`第${i / 2 + 1}轮: ${tigerNumber} (虎) vs ${dragonNumber} (龙) => ${result}胜`);
  }
  return {
    sum,
    dx,
    ds,
    labels,
    results
  };
}
function sscSumLH(numbers) {
  const sum = numbers.reduce((acc, cur) => acc + cur, 0);
  let dx = "小";
  let ds = "单";
  let lh = "虎";
  if (sum >= 12) {
    dx = "大";
  }
  if (sum % 2 == 0) {
    ds = "双";
  }
  if (numbers[0] > numbers[1]) {
    lh = "龙";
  }
  return { sum, dx, ds, lh };
}
function diffTime(time) {
  const openTime = dayjs.utc(time).utcOffset(8).format("YYYY-MM-DD HH:mm:ss");
  const currentTime = dayjs.utc().utcOffset(8).format("YYYY-MM-DD HH:mm:ss");
  return dayjs(openTime).diff(currentTime, "second");
}
function openTime(time) {
  return dayjs.utc(time).utcOffset(8).format("HH:mm:ss");
}
function parseQueryString(str) {
  var arr = [],
    length = 0,
    res = {},
    si = str.indexOf("?");
  str = str.substring(si + 1);
  arr = str.split("&");
  for (var i = 0; i < arr.length; i++) {
    res[arr[i].split("=")[0]] = arr[i].split("=")[1];
  }
  return res;
}
function pushArray(m) {
  var o = new Array();
  for (var n = 0; n < m.length; n++) {
    o.push(parseInt(m[n]));
  }
  return o;
}
function formatObject(m) {
  var o = "";
  for (var n = 0; n < m.length; n++) {
    if (n < m.length - 1) {
      o += m[n] + ",";
    } else {
      o += m[n];
    }
  }
  return o;
}
function getzf(a) {
  if (parseInt(a) < 10) {
    a = "0" + a;
  }
  return a;
}
function formatTime(m) {
  return (
    getzf(Math.floor(m / 60 / 60)) +
    ":" +
    getzf(Math.floor((m / 60) % 60)) +
    ":" +
    getzf(Math.floor(m % 60))
  );
}
// 构造函数
function AnimateLottery(obj) {
  this.localUrl = localStorage.getItem("OPEN_LIVE_URL") || "//" + location.host;
  this.lotteryId = obj.lotteryId;
  this.lotteryType = obj.lotteryType;
  this.lotteryName = decodeURIComponent(obj.lotteryName);
  this.isgameTime = true;
  this.countB = 0;
  this.setImage();
  this.init();
}
// 初始化
AnimateLottery.prototype.init = function () {
  var self = this;
  setTimeout(() => {
    self.eframe();
  }, 1000);
  self.getData(function (d) {
    self.startDown(d);
  });
};
// 获取数据ajax封装
AnimateLottery.prototype.getData = function (cb) {
  var self = this;
  $.ajax({
    url: self.localUrl + "/front/room/period",
    type: "post",
    dataType: "json",
    timeout: 15000,
    crossOriginIsolated: true,
    contentType: "application/json",
    headers: {
      Token: this.getToken() // 将 token 加到请求头
    },
    data: JSON.stringify({
      // 将数据对象转换为 JSON 字符串
      lottery_id: +self.lotteryId
    }),
    success: function (d) {
      cb && cb(d);
    }
  });
};
AnimateLottery.prototype.getToken = () => {
  const key = localStorage.getItem("STORE_KEY");
  const userStore = localStorage.getItem(key);
  if (userStore) {
    return JSON.parse(userStore).token;
  } else {
    return "";
  }
};
AnimateLottery.prototype.formatLuckCode = function (data) {
  var preDrawCode = data.LuckCode.split(",");
  for (var i = 0; i < preDrawCode.length; i++) {
    preDrawCode[i] = Number(preDrawCode[i]);
  }
  return preDrawCode;
};
// 首次加载处理
AnimateLottery.prototype.startDown = function (res) {
  var self = this;
  if (res.code == 200) {
    self.eframe();
    var data = res.data;
    switch (self.lotteryType) {
      case "sc":
        if (data.Status == 1) {
          self.formatData(data);
        } else {
          startcountdown(0);
          self.mountData({
            preDrawCode: [],
            numPeriods: data.LastNum.substr(-7),
            number: data.LastNum,
            sumNum: "",
            sumSingleDouble: "",
            sumBigSmall: "",
            tiger1: "",
            tiger2: "",
            tiger3: "",
            tiger4: "",
            tiger5: ""
          });
          self.setTime();
        }
        break;
      case "ssc":
        if (data.Status == 1) {
          self.formatData(data);
        } else {
          var numArr = self.formatLuckCode(data);
          sscAnimateEnd({
            counttime: 0,
            dragonTiger: "",
            drawTime: openTime(data.NextTime),
            id: "#numBig",
            preDrawCode: numArr,
            preDrawIssue: data.LastNum,
            sumBigSmall: "",
            sumNum: "",
            sumSingleDouble: ""
          });
          self.setTime();
        }
        break;
      case "pcdd":
        if (data.Status == 1) {
          self.formatData(data);
        } else {
          var numArr = self.formatLuckCode(data);
          var dataStr = {
            numArr: numArr,
            nextIssue: data.CurrentBitchNo,
            drawTime: openTime(data.NextTime),
            preDrawTime: formatTime(diffTime(data.NextTime))
          };
          pcEgg.startVid(dataStr);
          self.setTime();
        }
        break;
      default:
        break;
    }
  }
};
// 加载完组装数据到视图
AnimateLottery.prototype.mountData = function (n) {
  var self = this;
  switch (self.lotteryType) {
    case "sc":
      for (var m = 0; m < n.preDrawCode.length; m++) {
        $("body")
          .find("#pos" + (m + 1))
          .css("background-position", "0px " + (parseInt(n.preDrawCode[m]) - 1) * -64 + "px");
      }
      $("#currentdrawid").html(n.numPeriods);
      $("#nextdrawtime").html(n.number);
      $("#stat1_1").html(n.sumNum);
      $("#stat1_2").html(n.sumBigSmall);
      $("#stat1_3").html(n.sumSingleDouble);
      $("#stat2_1").html(n.tiger1);
      $("#stat2_2").html(n.tiger2);
      $("#stat2_3").html(n.tiger3);
      $("#stat2_4").html(n.tiger4);
      $("#stat2_5").html(n.tiger5);
      break;
    default:
      break;
  }
};
// 窗口大小变动处理
AnimateLottery.prototype.eframe = function () {
  this.resizeWindows();
};
// 重新请求获取数据
var m = null;
AnimateLottery.prototype.setTime = function () {
  var self = this;
  var m = setInterval(function () {
    self.countB++;
    if (!self.isgameTime) {
      if (self.countB == 3) {
        self.isgameTime = true;
        self.countB = 0;
      }
    } else {
      self.getData(function (res) {
        if (res.code == 200) {
          var data = res.data;
          if (data.Status == 1) {
            switch (self.lotteryType) {
              case "sc":
                var scNumArr = self.formatLuckCode(data);
                finishgame(formatObject(scNumArr));
                var o = setTimeout(function () {
                  self.formatData(data);
                  clearTimeout(o);
                  delete o;
                }, 10000);
                break;
              case "ssc":
                animateMethod.sscAnimate("#cqSsc");
                clearInterval(animateID["#cqSsc"]);
                delete animateID["#cqSsc"];
                self.formatData(data);
                break;
              case "pcdd":
                var pcddNumArr = self.formatLuckCode(data);
                clearInterval(pcEgg.stopRoate());
                pcEgg.startVid({
                  numArr: pcddNumArr,
                  nextIssue: data.CurrentBitchNo,
                  drawTime: openTime(data.NextTime),
                  preDrawTime: formatTime(diffTime(data.NextTime))
                });
                self.formatData(data);
                break;
              default:
                break;
            }
            clearInterval(m);
            delete m;
          } else {
            self.isgameTime = false;
          }
        }
      });
    }
  }, 2000);
};
// 设置开奖结果时间和属性
AnimateLottery.prototype.formatData = function (data) {
  var self = this;
  switch (self.lotteryType) {
    case "sc":
      startcountdown(Math.round(diffTime(data.NextTime)) - 1);
      var scNumbers = self.formatLuckCode(data);
      var sclhh = scSumLH(scNumbers);
      self.mountData({
        preDrawCode: scNumbers,
        numPeriods: data.CurrentBitchNo.substr(-3),
        number: data.LastNum,
        sumNum: sclhh.sum || "",
        sumSingleDouble: sclhh.ds || "",
        sumBigSmall: sclhh.dx || "",
        tiger1: sclhh.labels[0],
        tiger2: sclhh.labels[1],
        tiger3: sclhh.labels[2],
        tiger4: sclhh.labels[3],
        tiger5: sclhh.labels[4]
      });
      break;
    case "ssc":
      var sscNumbers = self.formatLuckCode(data);
      var ssclhh = sscSumLH(sscNumbers);
      sscAnimateEnd({
        counttime: diffTime(data.NextTime),
        dragonTiger: ssclhh.lh || "",
        drawTime: openTime(data.NextTime),
        id: "#numBig",
        preDrawCode: sscNumbers,
        preDrawIssue: data.LastNum,
        sumBigSmall: ssclhh.dx || "",
        sumNum: ssclhh.sum || "",
        sumSingleDouble: ssclhh.ds || ""
      });
      break;
    case "pcdd":
      var pcddNumbers = self.formatLuckCode(data);
      clearInterval(pcEgg.stopRoate());
      pcEgg.startVid({
        numArr: pcddNumbers,
        nextIssue: data.CurrentBitchNo,
        drawTime: openTime(data.NextTime),
        preDrawTime: formatTime(diffTime(data.NextTime))
      });
      break;
    default:
      break;
  }
  var m = setTimeout(function () {
    self.setTime();
    clearTimeout(m);
    delete m;
  }, diffTime(data.NextTime) * 1000);
};
// 公用直播窗口大小处理
AnimateLottery.prototype.resizeWindows = function () {
  var width = localStorage.getItem("appWidth");
  $("html").css({
    transform: "scale(1, 1)",
    "transform-origin": "left top",
    zoom: width / 1334
  });
};
// 设置logo
AnimateLottery.prototype.setImage = function () {
  var self = this;
  switch (self.lotteryType) {
    case "sc":
      $(".header .logo").html(self.lotteryName);
      break;
    case "ssc":
      $(".nameLogo .logo").html(self.lotteryName);
      break;
    case "pcdd":
      $("#logo").html(self.lotteryName);
      break;
    default:
      break;
  }
};
